<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="${ctx}/js/ext-3.3.0/resources/css/ext-all.css"/>
<link href="${ctx}/css/friendlist.css" media="screen" rel="stylesheet" type="text/css" />

<link href="${ctx}/css/css51.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${ctx}/js/ext-3.3.0/ext-base.js"></script>
<script type="text/javascript" src="${ctx}/js/ext-3.3.0/ext-all.js"></script>
<script type="text/javascript" src="${ctx}/js/ext-3.3.0/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="${ctx}/js/ajaxfileupload.js"></script>
<title>后台用户管理</title>
<script type="text/javascript">
	var rightList = [
		<#list rightList as right>
			<#if right_has_next>
				['${right.code!}','${right.text!}'],
			<#else>
				['${right.code!}','${right.text!}']
			</#if>
		</#list>
	];
	//根据权限code获取权限text
	function getRightText(code){
		for (var i = 0; i < rightList.length; i++) {
			//alert(rightList[i][0] + rightList[i][1]);
			if (rightList[i][0] == code) {
				return rightList[i][1];
			}
		}
		return "没有权限";
	}
	String.prototype.replaceAll = function(s1,s2) {
	   	return this.replace(new RegExp(s1,"gm"),s2);
	}
	//批量删除
	function listDelete(id){
		Ext.Msg.confirm('信息','确定要删除?',function(btn){
			if(btn == "yes"){
				$.ajax({
	    			url : "${ctx}/crmrole/ajax/deleteByIds",
	 				data:{
	    				ids:id
	 				},
	 				type:"post",
	 				success:function(data){
	 					if(data == 1){
	 						alert("操作成功");
	 						Ext.getCmp("grid2").getStore().removeAll();
		      				Ext.getCmp("grid2").getStore().load("${ctx}/crmrole/ajax/list");
	 						//document.location.reload();
	 					}else{
	 						alert("操作失败");
	 					}
	 				}
	 			});
			}
 		})
	}
	//全选 取消全选
	//params : all 全选复选框
	function reverseAllSelect(all){
		if(all.type == "checkbox" && all.checked == true){
			isReverseAllSelect(true);
		}else{
			isReverseAllSelect(false);
		}
	}
	function isReverseAllSelect(isSelect){
		var items = document.getElementsByTagName("input");
		for(var i=0;i<items.length;i++){
		    if(items[i].type == "checkbox"){
		        items[i].checked = isSelect;
		    }
	    }
	}
	//为复选框赋默认值
  	function cboInit(cboName,valueSet){
		var cbo = document.getElementsByName(cboName);
		for(var i = 0;i < cbo.length;i++){
		    if(valueSet.indexOf(cbo[i].value) != -1){
		    	cbo[i].checked = "checked";
		    }else{
				cbo[i].checked = "";
			}
		}
	}
	//获取复选框被选中值
  	function getCheckedValue(cboName){
  		var value = "";
		var cbo = document.getElementsByName(cboName);
		for(var i = 0;i < cbo.length;i++){
		    if(cbo[i].checked){
		    	value += cbo[i].value + ",";
		    }
	  	}
	  	return value == "" ? "" : value.substring(0,value.length-1);
  	}
	function setWinStyle(extWin,isHide){
		$("#"+extWin.el.id).css("z-index",isHide == false ? 0 : 9003);
		if (isHide) {
			extWin.hide();
		}
	}
	var list;
	function ajaxAddOrUpdate(){
		setWinStyle(win,false);
		$.ajax({
    		url : "${ctx}/crmrole/ajax/add",
 			data:{
    			id:entity.id,
    			name:encodeURIComponent($("#name").val()),
    			roleDesc:encodeURIComponent($("#roleDesc").val()),
    			flag:$("#flag").val(),
				buttons:bts
 			},
 			type:"post",
 			success:function(data){
 				if(data == 1){
					setWinStyle(win,true);
 					Ext.MessageBox.alert("提示","操作成功！");
 					store.reload();
 				}else if(data == 0){
 					Ext.MessageBox.alert("提示","您输入的角色名已存在，请重新输入！");
 				}else{
					setWinStyle(win,true);
					Ext.MessageBox.alert("提示","操作失败！");
				}
 			}
 		});
    }
	function clearData(){
		entity = {"id":0};
		$("#name").val("");
		$("#roleDesc").val("");
		$("#flag").val("1");
	}
	var entity = {"id":0};
	var win;
	var roleWin;//选择权限弹出窗口
	var saveCommand;
	function btnaddOrUpdateIssue_click(command,rowIndex,divId){
		cboInit("cboButton","");
		saveCommand = command;
		if(saveCommand == "add"){
			clearData();
		}else if(saveCommand.indexOf("edit") > -1){
			var tmp = list.getAt(rowIndex);
			entity.id = tmp.get("id");
			$("#name").val(tmp.get("name"));
			$("#roleDesc").val(tmp.get("roleDesc"));
			$("#flag").val(tmp.get("flag"));
			cboInit("cboButton",tmp.get("buttons"));
		}
		if(!win){
			win = new Ext.Window({
				id:"win",
				el:"hello-win",
				title:"操作",
				layout:'fit',
				width:500,
				height:200,
				hidden:true,
				resizable:false,
				closeAction:'hide',
				plain: true,
				contentEl : "nleft",
		        buttons: [
		        		{text:'保存',handler:  function(){ajaxAddOrUpdate();}},
					    {text: '取消',handler: function(){win.hide();}
						}]
			});
		}
		win.show();
	}
	//返回已选权限html
	function getRightHtml(rightCode,rightText){
		return "<li id='"+rightCode+"' class='fs_del'>" + 
				"<a class='fs_nor' hidefocus='true'>" + rightText + "</a>" + 
				"<a class='fs_state' title='删除' onclick='removeRoleHtml(\"" + rightCode +"\")'>删除</a>" + 
			"</li>";
	}
	//保存已选权限id,name
	var saveSelectRights = "";
	//添加权限至已选权限
	function addRoleHtml(rightCode,rightText){
		if(document.getElementById("frisel_"+rightCode).className != "fs_selected"){
			saveSelectRights += rightCode + ",";
			$("#frisel_"+rightCode).attr("class","fs_selected");
			$("#frisel_selectList").append(getRightHtml(rightCode,rightText));
		}
	}
	//移除已选权限
	function removeRoleHtml(code){
		//alert(saveSelectRights + "\n" + code+",");
		saveSelectRights = saveSelectRights.replace(code + ",", "");
		//alert(saveSelectRights + "\n" + code+",");
		$("#frisel_" + code).attr("class", "");
		$("#" + code).remove();
	}
	var saveRoleId = 0;
	//根据角色id 更新角色权限
	function updateUserRight(){
		setWinStyle(roleWin,false);
		saveSelectRights = saveSelectRights == "" ? "" : saveSelectRights.substring(0,saveSelectRights.length-1);
		//alert(saveSelectRights);return;
		$.ajax({
			url : "${ctx}/crmrole/ajax/updateUserRight",
			data:{
				roleId:saveRoleId,
				rights:saveSelectRights
			},
			type:"post",
			success:function(data){
				setWinStyle(roleWin,true);
				if(data == 1){
					Ext.MessageBox.alert("分配权限","更新成功");
					store.reload();
				}else{
					Ext.MessageBox.alert("分配权限","更新失败");
				}
			}
		});
	}
	//分配权限
	function selectRole(rowIndex){
		//清空所有已选权限(将样式名为fs_selected的元素的样式移除即可)
		$(".fs_selected").attr("class","");
		var tmp = list.getAt(rowIndex);
		saveRoleId = tmp.get("id");
		//首先获取该用户已有权限
		saveSelectRights = "";
		$.ajax({
			url : "${ctx}/crmrole/ajax/getByRoleId",
			data:{
				roleId:tmp.get("id")
			},
			type:"post",
			success:function(data){
				eval("var data=" + data);
				var li = "";
				for(var i = 0; i < data.options.length; i++){
					saveSelectRights += data.options[i].rightCode + ",";
					$("#frisel_"+data.options[i].rightCode).attr("class","fs_selected");
					li += getRightHtml(data.options[i].rightCode,getRightText(data.options[i].rightCode));
				}
				$("#frisel_selectList").html(li);
				if(!roleWin){
					roleWin = new Ext.Window({
						id:"roleWin",
						el:"role-win",
						title:"操作",
						layout:'fit',
						width:530,
						height:480,
						hidden:true,
						resizable:false,
						closeAction:'hide',
						plain: true,
						contentEl : "friendSelecter",
				        buttons: [
				        		{text:'保存',handler:  function(){updateUserRight();}},
							    {text: '取消',handler: function(){roleWin.hide();}
								}]
					});
				}
				roleWin.show();
			}
		});
	}
	var store;
	Ext.onReady(function(){
    	store = new Ext.data.Store({
	       	proxy:new Ext.data.HttpProxy({
	       		url: '${ctx}/crmrole/ajax/list'
	       	}),
	       	//读取数据源用json方法(三种方法1.读取json用JsonReader,2读取数组使用ArrayReader3.读取XML用XmlReader)
	       	reader:new Ext.data.JsonReader({
				root:"root",
	           	//从数据库中读取的总记录数
	           	totalProperty: 'count',
	           	fields:[
	                    'id','name','roleDesc','flag','buttons'
	                   ]
			})
		});
	
  		var bbar= new Ext.PagingToolbar({
	        pageSize: 25,
	        store: store,
	        loadMask: this.LoadMask,
	        displayInfo: true,
	        displayMsg: '当前为第[{0}]</span>条至第[{1}]条数据，共[{2}]条数据',
	        emptyMsg: "没有数据"
	    });
  		var sm = new Ext.grid.CheckboxSelectionModel();//复选框
		var cm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),
		  	sm,
          	{header: "id", width: 20, sortable: true, dataIndex: 'id'},
          	{header: "角色名称", width: 120, sortable: true, dataIndex: 'name'},
          	{header: "角色描述", width: 120, sortable: true, dataIndex: 'roleDesc'},
          	{header: "角色状态", width: 120, sortable: true, dataIndex: 'flag',
          		renderer:function(value){
          			if(value == 1){
						return "<span style='color:black'>启用</span>";
					}else{
						return "<span style='color:gray'>禁用</span>";
					}
        	  	}
          	},
          	{header: "操作", width: 120, sortable: true, dataIndex: 'id',id:"id",renderer:renderPromiseInfo,sortable:false}
    	]);
    	function renderPromiseInfo(value,cellmeta,record,rowIndex,columnIndex,store){
			cellmeta.attr =  'ext:qtitle="'  + "提示：" + '"'; 
			cellmeta.attr += 'ext:qtip="'  + "点击打开对应的承诺列表!" + '"'; 
			cellmeta.attr += 'ext:qwidth="150" ';
			var tmp = "<a style='color:blue;cursor:pointer' onclick='btnaddOrUpdateIssue_click(\"edit\","+rowIndex+",\"nleft\")'>更新</a>&nbsp;&nbsp;";
			tmp += "<a style='color:blue;cursor:pointer' onclick='selectRole(" + rowIndex + ")'>分配权限</a>&nbsp;&nbsp;";
			list = store;
			return tmp;
		}
		var apiTypes = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({
	            url:'${ctx}/crmrole/ajax/list'
	        }),  
	        reader:new Ext.data.ArrayReader({},[
	        	{name:'value'},
	        	{name:'text'}
	        ])
	        //reader:new Ext.data.JsonReader({},['apiType'])
	        //remoteSort: false
		});
    	apiTypes.load();
		var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"加载数据中,请等待......",store:store,removeMask :true});
	    var grid= new Ext.grid.GridPanel({
	    	id:'grid2',
	    	layout : 'fit',
	    	//自动适应宽高
	        //autoWidth:true,
	    	//autoHeight : true,
	        width:document.body.clientWidth,
	        height:document.documentElement.clientHeight,
	    	//指定div的ID
	    	//el:'pageGrid',
	    	maskText : '正在加载中...',
	     	getLoadMask : function(){
	         	if(this.LoadMask){
	          		return this.LoadMask;
	         	}else{
	          		this.LoadMask = new Ext.LoadMask(Ext.getBody(),{msg:this.maskText,removeMask : true});
	          		return this.LoadMask;
	         	}
	        },
	        setMaskText : function(msg){
	        	this.maskText = msg;
	        	this.getLoadMask().msg = this.maskText;
	        },
     		store:store,
     		tbar : [
         		//'关键字：',{id:'keyword',name:'keyword',xtype : 'textfield',emptyText :'按type查询',width:"150"},
         		'角色状态',new Ext.form.ComboBox({
        	 		id:'secFlag',
		        	name:'secFlag',
		        	hiddenId:'searchFlag',
		        	hiddenName:'searchFlag',
		        	store:new Ext.data.SimpleStore({
						fields:['value','text'],
						data:[[1,'启用'],[0,'禁用']]
					}),
         	 		valueField:'value',
          	 		displayField:'text',
          	 		emptyText : '请选择',
          	 		editable:false,
          	 		mode:'local',
          	 		listeners: {
	                	load: function() {
	                    	comboLocation.setValue(comboLocation.getValue());
	                	}
            		},
          	 		triggerAction:'all'
           		}),
         		'角色名称',new Ext.form.TextField({
        	 		id:"searchName",
        	 		name:'searchName',
           	 		valueField:'value',
           	 		displayField:'text',
           	 		editable:false,
           	 		mode:'local',
           	 		triggerAction:'all'
           		}),
         	" ",goAction," ",addAction," ",delAction],
         	cm:cm,
         	sm:sm,
         	//sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
         	viewConfig:{
          		forceFit: true
         	},  
         	frame:true,    
         	// 自动出现 expand/collapse toggle button, 上下收展的按纽   
         	titleCollapse: true, 
         	//collapsible: true,点击title也可以收展    
         	hideCollapseTool: true, 
         	//title:'用户投诉', // 表格标题    
         	header: false, 
         	// 不创建标题栏    
         	headerAsText: true, 
         	// 如果有标题栏, 隐藏标题栏    
         	iconCls:'icon-grid',  
         	//显示等待数据加载（loading）图标
         	loadMask: this.LoadMask,
         	//表格的工具栏    
         	/*tools:[ 
          	// 与title同一栏的按纽          
          	//{id:"save"},
          	{id:"help", 
          	handler:function(){
	          	Ext.Msg.alert('help','有问题？');}}, 
          	{id:"close",handler:function(){
     		Ext.Msg.alert('help','你想死啊');}}
           	// 按纽取值如下, close,minimize ,maximize ,restore ,gear ,pin ,unpin          
           	// toggle, down ,refresh ,minus ,plus ,help ,search ,save ,right ,left ,up  
          	],*/
          	//自带分页工具条
          	bbar: bbar
		});
		store.on('beforeload',function( store , options ){
			store.baseParams = {
          		//searchSourceCity:Ext.get("searchSourceCity").dom.value,
          		searchFlag:Ext.get("searchFlag").dom.value,
          		searchName:Ext.getCmp("searchName").getValue()
          		//searchDealWithStatus:Ext.get("searchDealWithStatus").dom.value
          		//Ext.get('searchSourceCity').getValue()
        		//keyword : Ext.getCmp('keyword').getValue();
         		//limit:grid.pagingConfig.pageSize;
          	};
       	 });
   		 grid.render("pageGrid");
    	 store.load({
    		 params:{start:0,limit:25},
    		 callback:function(data,options,success){
	        	for (var i = 0; i < store.getCount(); i++){
					 //alert(data[i].get('dfName'));
    			 }  
	        	
			}}
    	 );
    });
	var goAction = new Ext.Action({
	    text:"<img src='${ctx}/images/query.png'>",
	    tooltip:'查询角色',
	    handleMouseEvents : false,
	    pressed : true,
	    handler: function(){
			Ext.getCmp("grid2").getStore().removeAll();
	      	Ext.getCmp("grid2").getStore().load("/ajax/listApiTracLog.do");
	    }
    });
    var addAction = new Ext.Action({
	    text:"<img src='${ctx}/images/add.png'>",
	    tooltip:'添加角色',
	    handleMouseEvents : false,
	    pressed : true,
	    handler: function(){
			btnaddOrUpdateIssue_click('add',null,'nleft');
			//Ext.getCmp("grid2").getStore().removeAll();
	      	//Ext.getCmp("grid2").getStore().load("123123.do");
	    }
    });
    var delAction = new Ext.Action({
	    text:"<img src='${ctx}/images/delete.png'>",
	    tooltip:'删除角色',
	    handleMouseEvents : false,
	    pressed : true,
	    handler: function(){
			var selections = Ext.getCmp("grid2").getSelectionModel().getSelections();
			if(selections.length == 0 ){
			 	Ext.Msg.alert('错误','请选择要删除的数据');
				return ;
			}
			var ids = "";
			for(var i=0;i<selections.length;i++){
				ids += selections[i].get("id") + ",";
			}
			listDelete(ids.substring(0,ids.length-1));
	    }
    });
	function showRole(dtId){
		if($("#dd"+dtId).css("display")=="block"){
			$("#dt"+dtId).attr("class","");
			$('#dd'+dtId).hide();
		}else{
			$("#dt"+dtId).attr("class","on");
			$('#dd'+dtId).show();
		}
	}
</script>
</head>

<body>
	
	<div id="pageGrid"></div>
	<div id="role-win" class="x-hidden">
		<div class="layer_global friend_sel" id="friendSelecter" style="display: block; background-color: white;">
			<div class="layer_global_main"><!--516px 449px-->
				<div id="frisel_dropHandler" class="layer_global_title">
					<h3>
						<span class="jian">&gt;</span>选择好友
					</h3>
					<button class="bt_close" onclick="FriendSelecter.close()"
						title="关闭">
						<span class="none">╳</span>
					</button>
				</div>
				<div class="layer_global_cont">
					<!-- QQ好友 开始 -->
					<div class="gb_friend_selector_mod left"><!--516px 449px-->
						<div class="gb_friend_selector">
							<div class="gb_friend_selector_tit">
								<strong>所有权限</strong>
							</div>
							<div id="frisel_search" class="gb_friend_selector_cont gb_friend_selector_search">
								<!-- 搜索框 开始 -->
								<!--
								<div class="gb_friend_selector_search">
									<div class="fs_search">
										<input id="frisel_keyword" type="text" class="fs_hint"
											value="查找好友" onfocus="FriendSelecter.initSearch();"
											onkeyup="FriendSelecter.search()">
										<a class="fs_search_b" href="javascript:;" title="查找好友">搜索</a>
										<a class="fs_state" href="javascript: FriendSelecter.cancelSearch()" title="关闭搜索">关闭搜索</a>
									</div>
								</div>
								-->
								<!-- 好友列表 -->
								<div class="gb_friend_selector_list">
									<ul id="frisel_searchList" class="fs_fold fs_result"style="display: none;"></ul>
									<dl id="frisel_friendList" class="fs_fold fs_all_friend" style="display: block;">
										<#list rightList as right>
											<#if right.parentCode! == "0">
												<dt id="dt${right.code!}" onclick="showRole('${right.code!}')">
													<a href="javascript:;" hidefocus="true" id="a${right.code!}" class="fs_group">${right.text!}</a>
												</dt>
												<dd id="dd${right.code!}" style="display: none">
													<ul class="list_friend">
														<#list rightList as childRight>
															<#if childRight.parentCode! == right.code!>
																<li id="frisel_${childRight.code}" onclick="addRoleHtml('${childRight.code}','${childRight.text}')">
																	<a href="javascript:;" hidefocus="true" class="fs_nor" title="${childRight.rightDesc!}">${childRight.text!}</a>
																	<span class="fs_state">已选中</span>
																</li>
															</#if>
														</#list>
													</ul>
												</dd>
											</#if>
										</#list>
									</dl>
								</div>
							</div>
						</div>
					</div>
					<!-- 已选好友 开始 -->
					<div class="gb_friend_selector_mod right">
						<div class="gb_friend_selector">
							<div class="gb_friend_selector_tit">
								<strong>已选权限 <span id="frisel_numTips">（0/10）</span>
								</strong>
							</div>
							<div class="gb_friend_selector_cont">
								<div class="gb_friend_selector_list">
									<ul id="frisel_selectList" class="fs_fold">
										<!--<li class="fs_del">
											<a class="fs_nor" hidefocus="true">   此6位号出售`</a>
											<a class="fs_state" onclick="FriendSelecter.del(377481,0)">删除</a>
										</li>-->
									</ul>
								</div>
							</div>
						</div>
					</div>
					<div class="wrap_tips">
						<p id="frisel_tips" class="tips_text"></p>
						<div class="bt_wrap">
							<a id="frisel_yes" href="javascript:FriendSelecter.close();"
								class="bt_small"><strong>确 定</strong>
							</a>
							<a id="frisel_cancel" href="javascript:FriendSelecter.close()"
								class="bt_small"><strong>关闭</strong>
							</a>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- 新增/修改 -->
	<div id="hello-win" class="x-hidden">
		<div id="nleft" class="nleft" style="background: white;">
			<table width="482" border="0" cellpadding="0" cellspacing="0">
				<tbody>
					<tr bgcolor="#ECF1FA">
						<td width="100" height="30" align="center">角色名称</td>
						<td align="center"><input type="text" id="name" name="name"/></td>
						<td width="100" align="center">角色描述</td>
						<td><input type="text" id="roleDesc" name="roleDesc"/></td>
					</tr>
					<tr>
						<td width="100" height="30" align="center">当前状态</td>
						<td align="center">
							<select id="flag" name="flag" style="width:133px">
								<option selected="selected" value="1">启用</option>
								<option value="0">禁用</option>
							</select>
						</td>
						<td width="100" align="center"></td>
						<td></td>
					</tr>
				</tbody>
			</table>
		</div>
		<!--//------------------------------------------------------------------------------------------------------->
		
	</div>
</body>
</html>
